package com.zh.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zh.common.ErrorCode;
import com.zh.config.DomainConfig;
import com.zh.constant.UserConstant;
import com.zh.domain.dto.team.*;
import com.zh.domain.entity.*;
import com.zh.domain.vo.team.TeamUserHistoryVo;
import com.zh.domain.vo.team.TeamUserVo;
import com.zh.domain.vo.user.UserInTeamVo;
import com.zh.domain.vo.user.UserVO;
import com.zh.exception.ThrowUtils;
import com.zh.mapper.ProjectMapper;
import com.zh.mapper.TeamMapper;
import com.zh.mapper.UserMapper;
import com.zh.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author Administrator
 * @description 针对表【teams(团队表)】的数据库操作Service实现
 * @createDate 2025-02-09 16:21:55
 */
@Service
@Slf4j
public class TeamServiceImpl extends ServiceImpl<TeamMapper, Team> implements TeamService {
    @Resource
    private TeamMapper teamMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserService userService;
    @Resource
    private ProjectMapper projectMapper;
    @Resource
    private TeamUserService teamUserService;
    @Resource
    private TeamUserHistoryService teamUserHistoryService;

    @Resource
    private DomainConfig domainConfig;
    @Resource
    private ShortLinkService shortLinkService;
    @Resource
    private MessageService messageService;

    @Override
    @Transactional
    public boolean add(TeamAddRequest teamAddRequest) {
        //1.校验参数
        String name = teamAddRequest.getName();
        String description = teamAddRequest.getDescription();
        int maxMember = teamAddRequest.getMaxMember();
        paramsCheck(name, description, maxMember);
        //2.检查本用户是否创建过团队了
        int loginId = StpUtil.getLoginIdAsInt();
        LambdaQueryWrapper<Team> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Team::getOwnerId, loginId);
        Long count = teamMapper.selectCount(queryWrapper);
        ThrowUtils.throwIf(count > 0, ErrorCode.OPERATION_ERROR, "您已经创建过团队");
        //3.创建团队
        Team team = new Team();
        team.setName(name);
        team.setDescription(description);
        team.setOwnerId(loginId);
        team.setCreateBy(loginId);
        team.setUpdateBy(loginId);
        team.setMaxMember(maxMember);
        teamMapper.insert(team);
        //4.将用户提升为管理员
        User user = userMapper.selectById(loginId);
        User updateUser = new User();
        updateUser.setId(user.getId());
        List<String> roles = user.getRoles();
        if (!roles.contains(UserConstant.ADMIN)) {
            roles.add(UserConstant.ADMIN);
        }
        updateUser.setRoles(roles);
        userMapper.updateById(updateUser);
        //5.添加团队管理员记录
        TeamUser teamUser = new TeamUser();
        teamUser.setTeamId(team.getId());
        teamUser.setUserId(loginId);
        teamUser.setRole(1);
        teamUserService.save(teamUser);
        //6.添加团队历史记录
        TeamUserHistory teamUserHistory = new TeamUserHistory();
        teamUserHistory.setTeamId(team.getId());
        teamUserHistory.setCreateBy(loginId);
        teamUserHistory.setUpdateBy(loginId);
        teamUserHistory.setStatus(1);
        teamUserHistory.setResult(1);
        teamUserHistory.setType(2);
        teamUserHistoryService.save(teamUserHistory);
        return true;
    }

    @Override
    @Transactional
    public Boolean deleteTeam(Integer teamId) {
        //1.团队是否有项目关联
        LambdaQueryWrapper<Project> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Project::getTeamId, teamId);
        Long count = projectMapper.selectCount(queryWrapper);
        ThrowUtils.throwIf(count > 0, ErrorCode.OPERATION_ERROR, "团队有项目关联，无法删除");
        //2.删除团队
        boolean success = teamMapper.deleteById(teamId) > 0;
        //3.清除用户团队关联
        if (success) {
            teamUserService.removeById(teamId);
        }
        return true;
    }

    @Override
    public Boolean updateTeam(TeamUpdateRequest teamUpdateRequest) {
        //1.参数校验
        String name = teamUpdateRequest.getName();
        String description = teamUpdateRequest.getDescription();
        int maxMember = teamUpdateRequest.getMaxMember();
        paramsCheck(name, description, maxMember);
        int loginInt = StpUtil.getLoginIdAsInt();
        //2.更新团队信息
        Team team = BeanUtil.copyProperties(teamUpdateRequest, Team.class);
        team.setId(teamUpdateRequest.getTeamId());
        team.setUpdateBy(loginInt);
        teamMapper.updateById(team);
        return true;
    }

    @Override
    public Boolean inviteUser(TeamInviteRequest teamInviteRequest) {
        //1.校验参数
        Integer teamId = teamInviteRequest.getTeamId();
        List<Integer> userIds = teamInviteRequest.getUserIds();
        ThrowUtils.throwIf(null == teamId || userIds.isEmpty(), ErrorCode.PARAMS_ERROR);
        int loginId = StpUtil.getLoginIdAsInt();
        //2.是否已邀请
        LambdaQueryWrapper<TeamUser> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(TeamUser::getTeamId, teamId);
        List<TeamUser> teamUserList = teamUserService.list(queryWrapper1);
        List<Integer> timeUserIds = teamUserList.stream().map(TeamUser::getUserId).collect(Collectors.toList());
        //4.查找已经加入团队的用户的id
        List<Integer> existsId = userIds.stream().filter(timeUserIds::contains).collect(Collectors.toList());
        if (!existsId.isEmpty()) {
            String existsUsers = userMapper.selectBatchIds(existsId).stream().map(User::getName).collect(Collectors.toList()).toString();
            ThrowUtils.throwIf(StrUtil.isNotEmpty(existsUsers), ErrorCode.OPERATION_ERROR, existsUsers + "已加入团队");
        }
        //3.发送邀请
        List<TeamUserHistory> teamUserHistories = new ArrayList<>();
        for (Integer userId : userIds) {
            TeamUserHistory teamUserHistory = new TeamUserHistory();
            teamUserHistory.setTeamId(teamId);
            teamUserHistory.setInviterId(loginId);
            teamUserHistory.setInvitedId(userId);
            teamUserHistory.setType(1);
            teamUserHistory.setStatus(1);
            teamUserHistory.setCreateBy(loginId);
            teamUserHistory.setUpdateBy(loginId);
            teamUserHistories.add(teamUserHistory);
        }
        teamUserHistoryService.saveBatch(teamUserHistories);
        //4.发送消息
        User user = userMapper.selectById(loginId);
        String name = user.getName();
        Message message = new Message();
        message.setSendId(loginId);
        message.setContent(name + "邀请您加入团队,请前往团队页面确认");
        message.setStatus(1);
        message.setType(0);
        message.setNoticeType(0);
        message.setCreateBy(loginId);
        message.setUpdateBy(loginId);
        messageService.sendMessage(message, userIds);
        return true;
    }

    @Override
    public String generateInvite(Integer teamId) {
        //1.获取域名
        String webDomain = domainConfig.getWeb();
        //2.获取团队名称/团队长信息
        Team team = this.getById(teamId);
        String name = team.getName();
        Integer ownerId = team.getOwnerId();
        User user = userMapper.selectById(ownerId);
        String inviterName = user.getName();
        Integer inviterId = user.getId();
        //3.生成邀请链接
        String inviteUrl = webDomain + "/team/invite?teamId=" + teamId + "&name=" + name + "&inviterId=" + inviterId + "&inviterName=" + inviterName;
        //4.返回邀请链接
        return shortLinkService.generateShortLink(inviteUrl, domainConfig.getWeb(), 30, TimeUnit.MINUTES);
    }

    @Override
    @Transactional
    public String resolveInvite(String url) {
        //1.校验参数
        synchronized (url.intern()) {
            ThrowUtils.throwIf(StrUtil.isEmpty(url), ErrorCode.PARAMS_ERROR, "链接错误");
            String originalUrl = shortLinkService.resolveShortLink(url);
            Map<String, String> map = HttpUtil.decodeParamMap(originalUrl, StandardCharsets.UTF_8);
            if (map.containsKey("teamId") && map.containsKey("name") && map.containsKey("inviterName")) {
                String teamId = map.get("teamId");
                String name = map.get("name");
                String inviterName = map.get("inviterName");
                String inviterId = map.get("inviterId");
                //2.校验团队是否存在
                Team team = teamMapper.selectById(teamId);
                ThrowUtils.throwIf(team == null, ErrorCode.OPERATION_ERROR, "团队不存在");
                //3.校验团队成员是否已满
                boolean full = team.getMaxMember() <= teamUserService.count(new LambdaQueryWrapper<TeamUser>().eq(TeamUser::getTeamId, teamId));
                ThrowUtils.throwIf(full, ErrorCode.OPERATION_ERROR, "团队成员已满");
                //4.校验是否已加入团队
                int loginId = StpUtil.getLoginIdAsInt();
                boolean hasBeen = teamUserService.count(new LambdaQueryWrapper<TeamUser>().eq(TeamUser::getTeamId, teamId).eq(TeamUser::getUserId, loginId)) > 0;
                ThrowUtils.throwIf(hasBeen, ErrorCode.OPERATION_ERROR, "您已加入该团队");
                //5.确认添加
                TeamUser teamUser = new TeamUser();
                teamUser.setTeamId(Integer.valueOf(teamId));
                teamUser.setUserId(loginId);
                teamUser.setRole(0);
                teamUserService.save(teamUser);
                //6.添加记录
                TeamUserHistory teamUserHistory = new TeamUserHistory();
                teamUserHistory.setTeamId(Integer.valueOf(teamId));
                teamUserHistory.setInviterId(team.getOwnerId());
                teamUserHistory.setInvitedId(loginId);
                teamUserHistory.setType(1);
                teamUserHistory.setResult(1);
                teamUserHistory.setStatus(0);
                teamUserHistory.setCreateBy(loginId);
                teamUserHistory.setUpdateBy(loginId);
                teamUserHistoryService.save(teamUserHistory);
                //7.销毁短链
                shortLinkService.distroShortLink(url);
                //8.发送消息
                User user = userMapper.selectById(loginId);
                String userName = user.getName();
                Message message = new Message();
                message.setSendId(Integer.valueOf(inviterId));
                message.setCreateBy(Integer.valueOf(inviterId));
                message.setUpdateBy(Integer.valueOf(inviterId));
                message.setContent(userName + "已加入团队!");
                message.setNoticeType(0);
                message.setType(0);
                message.setStatus(1);
                messageService.sendMessage(message, List.of(loginId));
            }
            return "加入团队成功!";
        }
    }

    @Override
    public Boolean application(Integer teamId) {
        int loginId = StpUtil.getLoginIdAsInt();
        //1.判断是否已加入团队
        LambdaQueryWrapper<TeamUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeamUser::getTeamId, teamId).eq(TeamUser::getUserId, loginId);
        boolean exists = teamUserService.count(queryWrapper) > 0;
        ThrowUtils.throwIf(exists, ErrorCode.OPERATION_ERROR, "您已加入该团队");
        //2.是否有申请记录
        boolean application = teamUserHistoryService.count(new LambdaQueryWrapper<TeamUserHistory>()
                .eq(TeamUserHistory::getTeamId, teamId)
                .eq(TeamUserHistory::getInvitedId, loginId)
                .eq(TeamUserHistory::getStatus, 1)) > 0;
        ThrowUtils.throwIf(application, ErrorCode.OPERATION_ERROR, "等待管理员回复,请勿重复申请");
        //3.添加记录
        TeamUserHistory teamUserHistory = new TeamUserHistory();
        teamUserHistory.setTeamId(teamId);
        teamUserHistory.setApplicantId(loginId);
        teamUserHistory.setStatus(1);
        teamUserHistory.setCreateBy(loginId);
        teamUserHistory.setUpdateBy(loginId);
        teamUserHistoryService.save(teamUserHistory);
        return null;
    }

    @Override
    public Boolean auditApplication(TeamAuditRequest teamAuditRequest) {
        Integer id = teamAuditRequest.getId();
        Integer result = teamAuditRequest.getResult();
        int loginIdAsInt = StpUtil.getLoginIdAsInt();
        teamUserHistoryService.lambdaUpdate()
                .eq(TeamUserHistory::getId, id)
                .set(TeamUserHistory::getResult, result)
                .set(TeamUserHistory::getStatus, 0)
                .set(TeamUserHistory::getUpdateBy, loginIdAsInt)
                .set(TeamUserHistory::getUpdateBy, LocalDateTime.now())
                .update();
        return true;
    }

    @Override
    public Page<TeamUserHistoryVo> listTeamUserHistory(TeamUserHistoryPageRequest pageRequest) {
        // 1. 页码调整
        pageRequest.standardizeSize();
        Integer current = pageRequest.getCurrent();
        Integer pageSize = pageRequest.getPageSize();
        Integer teamId = pageRequest.getTeamId();
        Integer invitedId = pageRequest.getInvitedId();
        Integer applicantId = pageRequest.getApplicantId();
        Integer status = pageRequest.getStatus();
        LambdaQueryWrapper<TeamUserHistory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .orderByDesc(TeamUserHistory::getCreateAt)
                .orderByDesc(TeamUserHistory::getUpdateAt);
        // 添加 teamId 条件
        if (teamId != null) {
            queryWrapper.eq(TeamUserHistory::getTeamId, teamId);
        }
        // 添加 status 条件
        if (status != null) {
            queryWrapper.eq(TeamUserHistory::getStatus, status);
        }
        // 添加 invitedId 或 applicantId 条件
        if (invitedId != null || applicantId != null) {
            queryWrapper.and(wrapper -> {
                if (invitedId != null) {
                    wrapper.eq(TeamUserHistory::getInvitedId, invitedId);
                }
                if (applicantId != null) {
                    wrapper.or().eq(TeamUserHistory::getApplicantId, applicantId);
                }
            });
        }
        // 2. 分页查询
        Page<TeamUserHistory> page = new Page<>(current, pageSize);
        Page<TeamUserHistory> teamUserHistoryPage = teamUserHistoryService.page(page, queryWrapper);

        // 3. 记录转换为vo
        List<TeamUserHistory> records = teamUserHistoryPage.getRecords();
        List<TeamUserHistoryVo> teamUserHistoryVos = records.stream()
                .map(teamUserHistory -> BeanUtil.copyProperties(teamUserHistory, TeamUserHistoryVo.class))
                .collect(Collectors.toList());

        // 4. 获取记录中的所有teamId
        List<Integer> teamIds = teamUserHistoryVos.stream()
                .map(TeamUserHistoryVo::getTeamId)
                .distinct()
                .collect(Collectors.toList());

        // 5. 获取记录中的所有inviterId, invitedId, applicantId,removedId
        List<Integer> userIds = teamUserHistoryVos.stream()
                .flatMap(teamUserHistory -> {
                    Integer inviterId = teamUserHistory.getInviterId();
                    Integer invitedId1 = teamUserHistory.getInvitedId();
                    Integer applicantId1 = teamUserHistory.getApplicantId();
                    Integer removedId = teamUserHistory.getRemoveId();
                    Integer createBy = teamUserHistory.getCreateBy();
                    Integer updateBy = teamUserHistory.getUpdateBy();
                    return Stream.of(inviterId, invitedId1, applicantId1,
                                    removedId, createBy, updateBy)
                            .filter(Objects::nonNull);
                })
                .distinct()
                .collect(Collectors.toList());

        // 6. 并行查询团队名称和用户信息
        CompletableFuture<List<Team>> teamFuture = CompletableFuture.supplyAsync(() -> {
            if (teamIds.isEmpty()) {
                return Collections.emptyList();
            }
            return this.listByIds(teamIds);
        });
        CompletableFuture<List<User>> userFuture = CompletableFuture.supplyAsync(() -> {
            if (userIds.isEmpty()) {
                return Collections.emptyList();
            }
            return userService.listByIds(userIds);
        });

        // 7. 等待所有异步任务完成
        CompletableFuture.allOf(teamFuture, userFuture).join();

        // 8. 获取查询结果
        List<Team> teams = teamFuture.join();
        List<User> users = userFuture.join();

        // 9. 构建teamId到teamName的映射
        Map<Integer, String> teamNameMap = teams.stream()
                .collect(Collectors.toMap(Team::getId, Team::getName));

        // 10. 构建userId到userVO的映射
        Map<Integer, UserVO> userVOMap = users.stream()
                .map(User::toUserVo)
                .collect(Collectors.toMap(UserVO::getId, Function.identity()));

        // 11. 匹配teamName, inviter, invited, applicant
        teamUserHistoryVos.forEach(teamUserHistoryVo -> {
            Integer teamId1 = teamUserHistoryVo.getTeamId();
            teamUserHistoryVo.setTeamName(teamNameMap.get(teamId1));

            Integer inviterId1 = teamUserHistoryVo.getInviterId();
            if (inviterId1 != null) {
                teamUserHistoryVo.setInviter(userVOMap.get(inviterId1));
            }

            Integer invitedId1 = teamUserHistoryVo.getInvitedId();
            if (invitedId1 != null) {
                teamUserHistoryVo.setInvited(userVOMap.get(invitedId1));
            }

            Integer applicantId1 = teamUserHistoryVo.getApplicantId();
            if (applicantId1 != null) {
                teamUserHistoryVo.setApplicant(userVOMap.get(applicantId1));
            }
            Integer removeId = teamUserHistoryVo.getRemoveId();
            if (removeId != null) {
                teamUserHistoryVo.setRemover(userVOMap.get(removeId));
            }
            Integer createBy = teamUserHistoryVo.getCreateBy();
            if (createBy != null) {
                teamUserHistoryVo.setCreator(userVOMap.get(createBy));
            }
            Integer updateBy = teamUserHistoryVo.getUpdateBy();
            if (updateBy != null) {
                teamUserHistoryVo.setUpdater(userVOMap.get(updateBy));
            }
        });

        // 12. 组建结构
        Page<TeamUserHistoryVo> teamUserHistoryVoPage = new Page<>();
        teamUserHistoryVoPage.setRecords(teamUserHistoryVos);
        teamUserHistoryVoPage.setTotal(teamUserHistoryPage.getTotal());
        teamUserHistoryVoPage.setSize(teamUserHistoryPage.getSize());
        teamUserHistoryVoPage.setCurrent(teamUserHistoryPage.getCurrent());
        return teamUserHistoryVoPage;
    }

    @Override
    public List<TeamUserVo> getTeamUserVoByUserId() {
        int loginId = StpUtil.getLoginIdAsInt();
        List<TeamUser> teamUserList = teamUserService.lambdaQuery()
                .eq(TeamUser::getUserId, loginId)
                .list();

        if (teamUserList.isEmpty()) {
            return new ArrayList<>();
        }

        // 构建teamId teamUser map并处理潜在的key冲突
        Map<Integer, TeamUser> teamUserMap = teamUserList.stream()
                .collect(Collectors.toMap(
                        TeamUser::getTeamId,
                        teamUser -> teamUser,
                        (existing, replacement) -> existing // 处理key冲突，保留第一个
                ));

        // 直接通过teamUserList中的teamId查询teams
        List<Team> teams = teamMapper.selectBatchIds(teamUserList.stream()
                .map(TeamUser::getTeamId)
                .collect(Collectors.toList()));

        // 组件teamUserVoList
        return teams.stream()
                .map(team -> {
                    TeamUserVo teamUserVo = BeanUtil.copyProperties(team, TeamUserVo.class);
                    teamUserVo.setUserId(loginId);
                    teamUserVo.setRole(Optional.ofNullable(teamUserMap.get(team.getId()))
                            .map(TeamUser::getRole)
                            .orElse(null));
                    return teamUserVo;
                })
                .collect(Collectors.toList());
    }

    @Override
    public Page<UserInTeamVo> pageUserInTeam(UserInTeamRequest pageRequest) {
        //1. 参数检验
        Integer teamId = pageRequest.getTeamId();
        ThrowUtils.throwIf(null == teamId, ErrorCode.PARAMS_ERROR);
        //2. UserInTeamVo
        pageRequest.standardizeSize();
        Page<UserInTeamVo> page = new Page<>(pageRequest.getCurrent(), pageRequest.getPageSize());
        List<UserInTeamVo> pageList = teamMapper.pageUserInTeam(page, pageRequest);
        page.setRecords(pageList);
        return page;
    }

    @Override
    @Transactional
    public Boolean acceptInvite(AcceptInviteRequest acceptInviteRequest) {
        //1. 参数校验
        Integer id = acceptInviteRequest.getId();
        Integer invitedId = acceptInviteRequest.getInvitedId();
        Integer result = acceptInviteRequest.getResult();
        int loginId = StpUtil.getLoginIdAsInt();
        ThrowUtils.throwIf(null == id || null == invitedId || null == result, ErrorCode.PARAMS_ERROR);
        //2.修改邀请记录
        LambdaUpdateWrapper<TeamUserHistory> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(TeamUserHistory::getId, id)
                .eq(TeamUserHistory::getInvitedId, invitedId)
                .set(TeamUserHistory::getResult, result)
                .set(TeamUserHistory::getUpdateAt, LocalDateTime.now())
                .set(TeamUserHistory::getUpdateBy, loginId)
                .set(TeamUserHistory::getStatus, 0);

        boolean updated = teamUserHistoryService.update(updateWrapper);
        ThrowUtils.throwIf(!updated, ErrorCode.OPERATION_ERROR, "请勿重复加入");
        TeamUserHistory teamUserHistory = teamUserHistoryService.getById(id);
        Integer teamId = teamUserHistory.getTeamId();
        //3. 修改团队用户表
        if (result == 1) {
            TeamUser teamUser = new TeamUser();
            teamUser.setTeamId(teamId);
            teamUser.setUserId(invitedId);
            teamUser.setRole(0);
            try {
                teamUserService.save(teamUser);
            } catch (DuplicateKeyException e) {
                log.error("修改失败,数据库唯一索引冲突", e);
                ThrowUtils.throwIf(ErrorCode.OPERATION_ERROR, "请勿重复加入");
            }
        }
        return true;
    }

    @Override
    @Transactional
    public Boolean kickOut(TeamKickOutRequest teamKickOutRequest) {
        //1.参数检验
        Integer teamId = teamKickOutRequest.getTeamId();
        Integer userId = teamKickOutRequest.getUserId();
        int loginId = StpUtil.getLoginIdAsInt();
        String lock = teamId + "_" + userId + "_" + loginId;
        synchronized (lock.intern()) {
            ThrowUtils.throwIf(null == teamId || null == userId, ErrorCode.PARAMS_ERROR);
            //2.删除团队用户表记录
            LambdaQueryWrapper<TeamUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TeamUser::getTeamId, teamId)
                    .eq(TeamUser::getUserId, userId);
            teamUserService.remove(wrapper);
            //3.添加团队用户历史表记录
            TeamUserHistory teamUserHistory = new TeamUserHistory();
            teamUserHistory.setTeamId(teamId);
            teamUserHistory.setType(3);
            teamUserHistory.setRemoveId(userId);
            teamUserHistory.setCreateBy(loginId);
            teamUserHistory.setUpdateBy(loginId);
            teamUserHistory.setCreateAt(LocalDateTime.now());
            teamUserHistory.setUpdateAt(LocalDateTime.now());
            teamUserHistory.setStatus(0);
            teamUserHistory.setResult(1);
            teamUserHistoryService.save(teamUserHistory);
            //4.发送消息
            //4.1查询团队信息
            Team team = teamMapper.selectById(teamId);
            String teamName = team.getName();
            Message message = new Message();
            message.setStatus(1);
            message.setSendId(loginId);
            message.setCreateBy(loginId);
            message.setUpdateBy(loginId);
            message.setCreateAt(LocalDateTime.now());
            message.setUpdateAt(LocalDateTime.now());
            message.setNoticeType(0);
            message.setType(0);
            message.setContent("您已离开团队 " + teamName);
            messageService.sendMessage(message, List.of(userId));
            return true;
        }
    }

    @Override
    public Boolean isInTeam(Integer teamId, Integer userId) {
        LambdaQueryWrapper<TeamUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeamUser::getUserId, userId);
        queryWrapper.eq(TeamUser::getTeamId, teamId);
        return teamUserService.count(queryWrapper) > 0;
    }


    private void paramsCheck(String name, String description, int maxMember) {
        ThrowUtils.throwIf(name.length() > 32, ErrorCode.PARAMS_ERROR, "团队名称不多于32个字符");
        ThrowUtils.throwIf(description.length() > 300, ErrorCode.PARAMS_ERROR, "团队描述不多于300个字符");
        ThrowUtils.throwIf(maxMember < 1 || maxMember > 50, ErrorCode.PARAMS_ERROR, "团队成员人数1-50");
    }
}




